package com.utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @Auther: ChenJinEn
 * @Date: 2020/7/28 21:24
 * @Description: //TODO
 */
public abstract class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //请求路径的时候带个访问方法的名字就可以到具体的请求了
            // 比如  /user?method=login
            String md = request.getParameter("method");
            //换一个思考方式: 不写if  使用反射
            //反射,获取方法执行  md方法名
            Class clazz = this.getClass();
            //获取方法
            Method method = clazz.getMethod(md, HttpServletRequest.class, HttpServletResponse.class);
            //执行方法,对象,实际参数
            method.invoke(this, request, response);
            //允许AJAX跨域访问,把这个代码放入Filter中就可以跨域访问了
            //response.setHeader("Access-Control-Allow-Origin", "http://www.itheima331.com:8020");
            //AJAX访问允许客户端保存cookie
            //response.setHeader("Access-Control-Allow-Credentials","true");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}